<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 基站状态
const stationStatus = ref('idle') // idle, running, error
const statusMessage = computed(() => {
  const statusMap = {
    idle: '空闲',
    running: '运行中',
    error: '运行异常'
  }
  return statusMap[stationStatus.value]
})

// 交互信息
const interactionLogs = ref([])
function addLog(message) {
  const timestamp = new Date().toLocaleString()
  interactionLogs.value.push(`[${timestamp}] ${message}`)
  // 自动滚动到底部
  setTimeout(() => {
    const logElement = document.querySelector('.info-display')
    if (logElement) {
      logElement.scrollTop = logElement.scrollHeight
    }
  }, 100)
}

// 参数区域1：文件服务器配置
const fileProcessType = ref('')
const serverIp = ref('')
const intermediateDir = ref('')
const sourceDir = ref('')

// 参数区域2：基站参数配置
const selectedTemplate = ref('')
const transceiveMode = ref('')
const centerFrequency = ref('')
const cellId = ref('')
const rbStart = ref('')
const rbSize = ref('')
const mcs = ref('')
const ldpc = ref('')
const frameHeaderOffset = ref('')
const symbolStart = ref('')
const symbolNumber = ref('')
const additionalDmrsPosition = ref('')
const massiveMode = ref(false)

// 模板选项
const templateOptions = [
  { value: 'case001', label: 'case001(QPSK/wideband)' },
  { value: 'case002', label: 'case002(16QAM/wideband)' },
  { value: 'case003', label: 'case003(64QAM/wideband)' },
  { value: 'case007', label: 'case007(QPSK/smallband)' },
  { value: 'case008', label: 'case008(16QAM/smallband)' },
  { value: 'case009', label: 'case009(64QAM/smallband)' },
  { value: 'case101', label: 'case101(QPSK/wideband)' },
  { value: 'case102', label: 'case102(16QAM/wideband)' },
  { value: 'case103', label: 'case103(64QAM/wideband)' },
  { value: 'case107', label: 'case107(QPSK/smallband)' },
  { value: 'case108', label: 'case108(16QAM/smallband)' },
  { value: 'case109', label: 'case109(64QAM/smallband)' }
]

// 收发模式选项
const transceiveOptions = [
  { value: 'rx', label: 'rx（接收）' },
  { value: 'tx', label: 'tx（发送）' }
]

// 中心频点选项
const frequencyOptions = [
  { value: '3300870', label: '3300870' },
  { value: '3400860', label: '3400860' },
  { value: '350085', label: '350085' }
]

// MCS选项
const mcsOptions = Array.from({ length: 29 }, (_, i) => ({
  value: `${i}`,
  label: `${i}`
}))

// LDPC选项
const ldpcOptions = [
  { value: 'YES', label: 'YES' },
  { value: 'NO', label: 'NO' }
]

// 操作按钮处理函数
function startStation() {
  if (!validateAllParams()) {
    return
  }
  stationStatus.value = 'running'
  addLog('基站开始运行')
  addLog('参数配置：')
  addLog(`- 收发模式: ${transceiveMode.value}`)
  addLog(`- 中心频点: ${centerFrequency.value}`)
  addLog(`- 小区ID: ${cellId.value}`)
  addLog(`- RB Start: ${rbStart.value}`)
  addLog(`- RB Size: ${rbSize.value}`)
  addLog(`- MCS: ${mcs.value}`)
  addLog(`- LDPC: ${ldpc.value}`)
  // 显示成功消息
  ElMessage.success('基站已成功启动')
}

function stopStation() {
  stationStatus.value = 'idle'
  addLog('基站已停止')
  ElMessage.success('基站已成功停止')
}

function hardReboot() {
  stationStatus.value = 'idle'
  addLog('执行硬重启操作')
  ElMessage.success('硬重启命令已发送')
}

function softReboot() {
  stationStatus.value = 'running'
  addLog('执行软重启操作')
  ElMessage.success('软重启命令已发送')
}

// 下发配置
function submitConfig() {
  // 检查IP是否能ping通（模拟）
  if (!validateIpAddress(serverIp.value)) {
    addLog('错误：文件服务器IP格式不正确')
    ElMessage.error('文件服务器IP格式不正确')
    return
  }
  
  // 模拟ping测试
  const canPing = Math.random() > 0.2 // 80%概率能ping通
  if (!canPing) {
    addLog('错误：无法ping通文件服务器')
    ElMessage.error('无法ping通文件服务器')
    return
  }
  
  if (!validateFileParams()) {
    return
  }
  
  addLog('配置已成功下发')
  addLog(`- 文件处理方式: ${fileProcessType.value}`)
  addLog(`- 服务器IP: ${serverIp.value}`)
  addLog(`- 中间文件存放目录: ${intermediateDir.value}`)
  addLog(`- 发端文件目录: ${sourceDir.value}`)
  ElMessage.success('配置已成功下发')
}

// 模板选择处理
function handleTemplateSelect() {
  if (!selectedTemplate.value) return
  
  // 根据选择的模板设置默认参数
  // 这里只是模拟，实际应该根据模板定义设置不同参数
  const templateData = {
    transceiveMode: 'tx',
    centerFrequency: '3300870',
    cellId: '1',
    rbStart: '0',
    rbSize: '50',
    mcs: '10',
    ldpc: 'YES',
    frameHeaderOffset: '0',
    symbolStart: '0',
    symbolNumber: '14',
    additionalDmrsPosition: '0'
  }
  
  // 根据模板类型调整参数
  if (selectedTemplate.value.includes('QPSK')) {
    templateData.mcs = '5'
  } else if (selectedTemplate.value.includes('16QAM')) {
    templateData.mcs = '12'
  } else if (selectedTemplate.value.includes('64QAM')) {
    templateData.mcs = '20'
  }
  
  if (selectedTemplate.value.includes('smallband')) {
    templateData.rbSize = '25'
  }
  
  // 设置参数
  transceiveMode.value = templateData.transceiveMode
  centerFrequency.value = templateData.centerFrequency
  cellId.value = templateData.cellId
  rbStart.value = templateData.rbStart
  rbSize.value = templateData.rbSize
  mcs.value = templateData.mcs
  ldpc.value = templateData.ldpc
  frameHeaderOffset.value = templateData.frameHeaderOffset
  symbolStart.value = templateData.symbolStart
  symbolNumber.value = templateData.symbolNumber
  additionalDmrsPosition.value = templateData.additionalDmrsPosition
  
  addLog(`已选择模板：${templateOptions.find(t => t.value === selectedTemplate.value)?.label}`)
}

// 选择目录（模拟）
function selectDirectory() {
  // 在实际应用中，这里应该打开文件选择器
  intermediateDir.value = 'C:\\temp\\intermediate'
  addLog(`已选择中间文件存放目录: ${intermediateDir.value}`)
}

// 验证函数
function validateIpAddress(ip) {
  const ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  return ipRegex.test(ip)
}

function validateFileParams() {
  if (!fileProcessType.value) {
    ElMessage.error('请选择文件处理方式')
    return false
  }
  if (!serverIp.value) {
    ElMessage.error('请输入服务器IP')
    return false
  }
  if (!intermediateDir.value) {
    ElMessage.error('请选择中间文件存放目录')
    return false
  }
  if (!sourceDir.value) {
    ElMessage.error('请输入发端文件目录')
    return false
  }
  return true
}

function validateAllParams() {
  // 验证文件参数
  if (!validateFileParams()) {
    return false
  }
  
  // 验证基站参数
  if (!transceiveMode.value) {
    ElMessage.error('请选择收发模式')
    return false
  }
  if (!centerFrequency.value) {
    ElMessage.error('请选择中心频点')
    return false
  }
  if (!cellId.value || isNaN(cellId.value)) {
    ElMessage.error('请输入有效的小区ID')
    return false
  }
  if (!rbStart.value || isNaN(rbStart.value)) {
    ElMessage.error('请输入有效的RB Start')
    return false
  }
  if (!rbSize.value || isNaN(rbSize.value)) {
    ElMessage.error('请输入有效的RB Size')
    return false
  }
  
  // 检查RB Start + RB Size ≤ 273
  const rbStartNum = parseInt(rbStart.value)
  const rbSizeNum = parseInt(rbSize.value)
  if (rbStartNum + rbSizeNum > 273) {
    ElMessage.error('RB Start + RB Size 必须小于等于273')
    return false
  }
  
  if (!mcs.value) {
    ElMessage.error('请选择MCS')
    return false
  }
  if (!ldpc.value) {
    ElMessage.error('请选择LDPC')
    return false
  }
  if (!frameHeaderOffset.value || isNaN(frameHeaderOffset.value) || parseInt(frameHeaderOffset.value) < 0) {
    ElMessage.error('请输入有效的帧头偏移量(正整数)')
    return false
  }
  if (!symbolStart.value || isNaN(symbolStart.value)) {
    ElMessage.error('请输入有效的Symbol Start')
    return false
  }
  if (!symbolNumber.value || isNaN(symbolNumber.value)) {
    ElMessage.error('请输入有效的Symbol Number')
    return false
  }
  if (!additionalDmrsPosition.value || isNaN(additionalDmrsPosition.value)) {
    ElMessage.error('请输入有效的Additional DMRS Position')
    return false
  }
  
  return true
}
</script>

<template>
  <div class="base-station-management">
    <!-- 上方边框区域 -->
    <div class="top-section" style="margin-bottom: 20px;">
      <div style="display: flex; align-items: center; margin-bottom: 10px;">
        <span style="font-weight: bold; margin-right: 10px;">基站状态：</span>
        <span class="status-indicator" :class="`status-${stationStatus}`"></span>
        <span>{{ statusMessage }}</span>
      </div>
      <div style="display: flex;">
        <el-button 
          type="primary" 
          class="action-button" 
          @click="startStation"
          :disabled="stationStatus === 'running'"
        >
          开始
        </el-button>
        <el-button 
          type="danger" 
          class="action-button" 
          @click="stopStation"
          :disabled="stationStatus === 'idle'"
        >
          停止
        </el-button>
        <el-button 
          class="action-button" 
          @click="hardReboot"
        >
          硬重启
        </el-button>
        <el-button 
          class="action-button" 
          @click="softReboot"
        >
          软重启
        </el-button>
      </div>
    </div>

    <!-- 交互信息显示区 -->
    <div class="info-display">
      <p v-for="(log, index) in interactionLogs" :key="index" style="margin: 2px 0;">{{ log }}</p>
    </div>

    <!-- 参数选择区域1：文件服务器配置 -->
    <div class="form-section">
      <h3 style="margin-bottom: 15px;">文件服务器配置</h3>
      <el-form ref="fileForm" label-width="120px" :inline="false">
        <el-form-item label="文件处理方式" prop="fileProcessType">
          <el-select v-model="fileProcessType" placeholder="请选择文件处理方式" style="width: 200px;">
            <el-option label="编码" value="encode"></el-option>
            <el-option label="解码" value="decode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务器IP" prop="serverIp">
          <el-input v-model="serverIp" placeholder="请输入服务器IP" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="中间文件存放目录" prop="intermediateDir">
          <el-input v-model="intermediateDir" placeholder="请选择目录" style="width: 280px;"></el-input>
          <el-button @click="selectDirectory" style="margin-left: 10px;">选择</el-button>
        </el-form-item>
        <el-form-item label="发端文件目录" prop="sourceDir">
          <el-input v-model="sourceDir" placeholder="请输入发端文件目录" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitConfig">下发配置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 参数选择区域2：基站参数配置 -->
    <div class="form-section">
      <h3 style="margin-bottom: 15px;">基站参数配置</h3>
      
      <!-- 模板选择 -->
      <el-form-item label="选择模板" style="margin-bottom: 15px;">
        <el-select 
          v-model="selectedTemplate" 
          placeholder="请选择模板（可选）" 
          style="width: 300px;"
          @change="handleTemplateSelect"
        >
          <el-option 
            v-for="template in templateOptions" 
            :key="template.value" 
            :label="template.label" 
            :value="template.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form ref="stationForm" label-width="120px" :inline="false">
            <el-form-item label="收发模式" prop="transceiveMode">
              <el-select v-model="transceiveMode" placeholder="请选择收发模式" style="width: 200px;">
                <el-option 
                  v-for="option in transceiveOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="中心频点" prop="centerFrequency">
              <el-select v-model="centerFrequency" placeholder="请选择中心频点" style="width: 200px;">
                <el-option 
                  v-for="option in frequencyOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="小区ID" prop="cellId">
              <el-input 
                v-model="cellId" 
                placeholder="请输入小区ID" 
                style="width: 200px;"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="RB Start" prop="rbStart">
              <el-input 
                v-model="rbStart" 
                placeholder="请输入RB Start" 
                style="width: 200px;"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="RB Size" prop="rbSize">
              <el-input 
                v-model="rbSize" 
                placeholder="请输入RB Size" 
                style="width: 200px;"
                type="number"
                min="1"
              ></el-input>
              <span style="color: #909399; margin-left: 10px;">RB Start + RB Size ≤ 273</span>
            </el-form-item>
            <el-form-item label="MCS" prop="mcs">
              <el-select v-model="mcs" placeholder="请选择MCS" style="width: 200px;">
                <el-option 
                  v-for="option in mcsOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="LDPC" prop="ldpc">
              <el-select v-model="ldpc" placeholder="请选择LDPC" style="width: 200px;">
                <el-option 
                  v-for="option in ldpcOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <el-form label-width="160px" :inline="false">
            <el-form-item label="帧头偏移量(us)" prop="frameHeaderOffset">
              <el-input 
                v-model="frameHeaderOffset" 
                placeholder="请输入帧头偏移量" 
                style="width: 200px;"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="Symbol Start" prop="symbolStart">
              <el-input 
                v-model="symbolStart" 
                placeholder="请输入Symbol Start" 
                style="width: 200px;"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="Symbol Number" prop="symbolNumber">
              <el-input 
                v-model="symbolNumber" 
                placeholder="请输入Symbol Number" 
                style="width: 200px;"
                type="number"
                min="1"
              ></el-input>
            </el-form-item>
            <el-form-item label="Additional DMRS Position" prop="additionalDmrsPosition">
              <el-input 
                v-model="additionalDmrsPosition" 
                placeholder="请输入Additional DMRS Position" 
                style="width: 200px;"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="massiveMode">海量模式</el-checkbox>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.base-station-management {
  height: 100%;
  overflow: auto;
}

.top-section {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>